package org.example.ruoxing_admin_springboot3.utils;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
/**
 * @description Aes加密工具类
 * @author 莫若省
 * @createTime 2024/5/9
*/
public class AesEncryptUtils {
    /**
     * 使用AES-128-CBC加密模式，key需要为16位,key和iv可以相同，也可以不同!
     */
    private static final String KEY = "CMDDTYDF&WY196KJ";
    private static final String IV = "CMDDTYDF&WY196KJ";
    /**
     * 算法/模式/补码方式
     */
    private static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";
    private static final String AES_ENC = "AES";
    /**
     * 加密方法
     * @param data 要加密的数据
     * @return 加密的结果
     */
    public static String encrypt(String data){
        try {
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
            int blockSize = cipher.getBlockSize();
            byte[] dataBytes = data.getBytes();
            int plaintextLength = dataBytes.length;
            if (plaintextLength % blockSize != 0) {
                plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));
            }
            byte[] plaintext = new byte[plaintextLength];
            System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), AES_ENC);
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
            byte[] encrypted = cipher.doFinal(plaintext);
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解密方法
     * @param data 解密的数据
     * @return 解密的结果
     */
    public static String decrypt(String data) {
        try {
            byte[] encrypted1 = Base64.getDecoder().decode(data);
            Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
            SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), AES_ENC);
            IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original).trim();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @description 测试方法
     * @author 莫若省
     * @createTime 2024/5/9
    */

    public static void main(String[] args) {
        String data = "Hello, World!";
        String encrypted = AesEncryptUtils.encrypt(data);
        System.out.println("加密后的数据：" + encrypted);
        String decrypted = AesEncryptUtils.decrypt(encrypted);
        System.out.println("解密后的数据：" + decrypted);
    }
}
